/**
 * FileFind - ftp/shares indexing and search php engine
 * Module: persist-jpa20
 * Description: Persistence implementation with JPA 2.0
 * Copyright (c) 2003-2010 Rage Steel, www.gt2.ru
 */
package ru.ffind.persist.jpa20.service;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import ru.ffind.persist.jpa20.bean.AbstractEntityManagerFactoryBean;

/**
 * Abstract class for services.
 *
 * @author Rage Steel
 */
public abstract class AbstractServiceImpl {

    private AbstractEntityManagerFactoryBean entityManagerFactoryBean;

    public void setEntityManagerFactoryBean(AbstractEntityManagerFactoryBean entityManagerFactoryBean) {
        this.entityManagerFactoryBean = entityManagerFactoryBean;
    }

    protected EntityManager createEntityManager() {
        return entityManagerFactoryBean.createEntityManager();
    }

    protected static <T> CriteriaQuery<T> createCriteriaQuery(
            EntityManager entityManager, Class<T> clazz) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(clazz);
        Root<T> host = criteriaQuery.from(clazz);
        criteriaQuery.select(host);
        return criteriaQuery;
    }

    protected static <T> TypedQuery<T> createTypedQuery(
            EntityManager entityManager, Class<T> clazz) {
        CriteriaQuery<T> criteriaQuery = createCriteriaQuery(entityManager, clazz);
        return entityManager.createQuery(criteriaQuery);
    }

}
